/**
 * http协议请求
 */
import request from './request'
import CommonUtil from './commonUtil'


// 返回状态码
export enum ContentType {
  REQUEST_JSON = 'application/json', // json
  REQUEST_FORM = 'application/x-www-form-urlencoded', // 表单
  REQUEST_FORM_FILE = 'multipart/form-data', // 文件表单
}

export enum HttpMethod {
  GET = 'get',
  POST = 'post',
  DELETE = 'delete',
  PUT = 'put',
}


/**
 * 请求class
 */
class HttpRequest {
 

  // get 请求
  public static get<T>(url: string, data?: object): Promise<T> {
    return request<any, T>({
      url: url,
      method: HttpMethod.GET,
      params: data,
    });
  }
  // 同步请求json
  public static async postSync<T>(url: string, data: object): Promise<T> {
    const result:T = await HttpRequest.post(url, data);
    return result;
  }

  // 同步请求json
  public static post<T>(url: string, data?: object): Promise<T> {
    return request<any, T>({
      url: url,
      method: HttpMethod.POST,
      data: data,
    });
  }



  // post form 上传文件和表单
  public static postFormData<T>(url: string, data: FormData): Promise<T> {
    return request<any, T>({
      url: url,
      method: HttpMethod.POST,
      data: data,
      headers: {
        "Content-Type": ContentType.REQUEST_FORM_FILE,
      },
    });
  }

    // post form 上传文件和表单
    public static postFileForm<T>(url: string, data?: Object): Promise<T> {
      const formData = new FormData();
      if (data) {
        for (const key in data) {
          const value = (data as any)[key];
          if (Array.isArray(value)) {
            value.forEach((item, index) => {
              if (key == 'files') {
                formData.append(key, item['raw']);
              } else {
                // formData.append(`${key}[${index}]`, item);
                formData.append(key, item);
              }
              
          });
          } else if (value instanceof File || value instanceof Blob) {
            formData.append(key, (value as File));
          } else if (value !== undefined && value !== null) {
            formData.append(key, value);
          } else {
            formData.append(key, value);
          }
        }
      }
      return request<any, T>({
        url: url,
        method: HttpMethod.POST,
        data: formData,
        headers: {
          "Content-Type": ContentType.REQUEST_FORM_FILE,
        },
      });
    }


}

export default HttpRequest
